/*
 *
 *   INSPINIA - Responsive Admin Theme
 *   version 2.9.2
 *
 */


$(document).ready(function () {

    // Fast fix bor position issue with Propper.js
    // Will be fixed in Bootstrap 4.1 - https://github.com/twbs/bootstrap/pull/24092
    Popper.Defaults.modifiers.computeStyle.gpuAcceleration = false;


    // Add body-small class if window less than 768px
    if ($(window).width() < 769) {
        $('body').addClass('body-small')
    } else {
        $('body').removeClass('body-small')
    }

    $('#index_center').load("/center");

    buildLoginUserInfo()

    $('.logout').on('click', function (e) {
        $.mySwalConfirm('确认要注销登录？', function () {
            $.post("/logout", {}, function (data) {
                if (data && data.code === 0) {
                    window.location.href = "/";
                } else {
                    toastr.error(data.msg, '操作失败')
                }
            })
        });
    })

    // Collapse ibox function
    $('.collapse-link').on('click', function (e) {
        e.preventDefault();
        var ibox = $(this).closest('div.ibox');
        var button = $(this).find('i');
        var content = ibox.children('.ibox-content');
        content.slideToggle(200);
        button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
        ibox.toggleClass('').toggleClass('border-bottom');
        setTimeout(function () {
            ibox.resize();
            ibox.find('[id^=map-]').resize();
        }, 50);
    });

    // Close ibox function
    $('.close-link').on('click', function (e) {
        e.preventDefault();
        var content = $(this).closest('div.ibox');
        content.remove();
    });

    // Fullscreen ibox function
    $('.fullscreen-link').on('click', function (e) {
        e.preventDefault();
        var ibox = $(this).closest('div.ibox');
        var button = $(this).find('i');
        $('body').toggleClass('fullscreen-ibox-mode');
        button.toggleClass('fa-expand').toggleClass('fa-compress');
        ibox.toggleClass('fullscreen');
        setTimeout(function () {
            $(window).trigger('resize');
        }, 100);
    });

    // Close menu in canvas mode
    $('.close-canvas-menu').on('click', function (e) {
        e.preventDefault();
        $("body").toggleClass("mini-navbar");
        SmoothlyMenu();
    });

    // Run menu of canvas
    $('body.canvas-menu .sidebar-collapse').slimScroll({
        height: '100%',
        railOpacity: 0.9
    });

    // Open close right sidebar
    $('.right-sidebar-toggle').on('click', function (e) {
        e.preventDefault();
        $('#right-sidebar').toggleClass('sidebar-open');
    });

    // Initialize slimscroll for right sidebar
    $('.sidebar-container').slimScroll({
        height: '100%',
        railOpacity: 0.4,
        wheelStep: 10
    });

    // Open close small chat
    $('.open-small-chat').on('click', function (e) {
        e.preventDefault();
        $(this).children().toggleClass('fa-comments').toggleClass('fa-times');
        $('.small-chat-box').toggleClass('active');
    });

    // Initialize slimscroll for small chat
    $('.small-chat-box .content').slimScroll({
        height: '234px',
        railOpacity: 0.4
    });

    // Small todo handler
    $('.check-link').on('click', function () {
        var button = $(this).find('i');
        var label = $(this).next('span');
        button.toggleClass('fa-check-square').toggleClass('fa-square-o');
        label.toggleClass('todo-completed');
        return false;
    });

    // Append config box / Only for demo purpose
    // Uncomment on server mode to enable XHR calls
    //$.get("skin-config.html", function (data) {
    //    if (!$('body').hasClass('no-skin-config'))
    //        $('body').append(data);
    //});

    // Minimalize menu
    $('.navbar-minimalize').on('click', function (event) {
        event.preventDefault();
        $("body").toggleClass("mini-navbar");
        SmoothlyMenu();

    });

    // Tooltips demo
    $('.tooltip-demo').tooltip({
        selector: "[data-toggle=tooltip]",
        container: "body"
    });


    // Move right sidebar top after scroll
    $(window).scroll(function () {
        if ($(window).scrollTop() > 0 && !$('body').hasClass('fixed-nav')) {
            $('#right-sidebar').addClass('sidebar-top');
        } else {
            $('#right-sidebar').removeClass('sidebar-top');
        }
    });

    $("[data-toggle=popover]").popover();

    // Add slimscroll to element
    $('.full-height-scroll').slimscroll({
        height: '100%'
    })

    $('#index_loading').hide();
    $('#wrapper').show();
    $('body').removeClass('gray-bg');
});

// Minimalize menu when screen is less than 768px
$(window).bind(" resize", function () {
    if ($(this).width() < 769) {
        $('body').addClass('body-small')
    } else {
        $('body').removeClass('body-small')
    }
});

// Fixed Sidebar
$(window).bind("load", function () {
    if ($("body").hasClass('fixed-sidebar')) {
        $('.sidebar-collapse').slimScroll({
            height: '100%',
            railOpacity: 0.9
        });
    }
});

// Minimalize menu when screen is less than 768px
$(window).bind("load resize", function () {
    if ($(this).width() < 769) {
        $('body').addClass('body-small')
    } else {
        $('body').removeClass('body-small')
    }
});

function centerLoad(url, menuId, menuName, hasHeader, isSingle = false) {
    $('[data-toggle="tooltip"]').tooltip('dispose')
    $('#index_center').empty()
    if (hasHeader=='false') {
        $('.page-heading').hide()
    } else {
        // 设置页头
        if(isSingle){
            $('.page-heading-title').text(menuName)
            $('.breadcrumb').empty().append(buildBreadcrumbItem("/", "首页", false));
            $('.breadcrumb').append(buildBreadcrumbItem("#", menuName, true));
        } else {
            let myMenuId = menuId ? menuId : menuIdCur;
            let menus = getMenuPath(myMenuId);
            if (menus.length > 0) {
                $('.page-heading-title').text(menus[menus.length - 1].name)
                $('.breadcrumb').empty().append(buildBreadcrumbItem("/", "首页", false));
                for (let i in menus) {
                    if (i == menus.length - 1) {
                        $('.breadcrumb').append(buildBreadcrumbItem("#", menus[i].name, menuId ? true : false));
                    } else {
                        $('.breadcrumb').append(buildBreadcrumbItem("#", menus[i].name, false));
                    }
                }
                if (menuName) {
                    $('.breadcrumb').append(buildBreadcrumbItem("#", menuName, true));
                }
            }
        }
        $('.page-heading').show()
    }

    $('#index_center').load(url, {}, function (responseText, textStatus, XMLHttpRequest) {
        //console.log(responseText, textStatus, XMLHttpRequest)
        if (textStatus == 'error') {
            if(XMLHttpRequest.status == 404){
                window.location.href = "/404";
                return false;
            } else if(XMLHttpRequest.status == 401){
                $.mySwalWarn("登录过期，请重新登录", function () {
                    window.location.href = "/login";
                });
                return false;
            }
        }
    });
}

function iframeLoad(iframe) {
    $(iframe).height($('#page-wrapper').height() - 61 - 40.5);
}

var menuList = [];
var menuIdCur = undefined;

function getMenuPath(menuId) {
    menuIdCur = menuId;
    return getMenuPathPri(menuList, menuId);
}

// 得到菜单链集合
function getMenuPathPri(arrs, menuId) {
    let menuPath = [];
    for (let i in arrs) {
        if (arrs[i].menuId == menuId) {
            menuPath.push({
                menuId: arrs[i].menuId,
                name: arrs[i].name
            });
            break;
        }
        if (arrs[i].list != null) {
            let subMenuPath = getMenuPathPri(arrs[i].list, menuId);
            if (subMenuPath.length > 0) {
                menuPath.push({
                    menuId: arrs[i].menuId,
                    name: arrs[i].name
                });
                menuPath = menuPath.concat(subMenuPath);
                break;
            }
        }
    }
    return menuPath;
}

function buildBreadcrumbItem(url, name, isActive) {
    let myLi = $('<li class="breadcrumb-item"/>')
    let myA = $('<a href="' + url + '"/>');
    if (isActive) {
        myLi.addClass("active")
        let myStrong = $('<strong/>')
        myStrong.text(name)
        myA.append(myStrong)
    } else {
        myA.text(name)
    }
    myLi.append(myA);
    return myLi;
}

function buildLoginUserInfo(){
    $.myGet({
        url: `/myInfo`,
        success: function (data) {
            if (data && data.code === 0) {
                let name = data.userInfo.username;
                if(data.userInfo.name){
                    name = data.userInfo.name;
                }
                $('#loginUser').text(name)
            } else {
                toastr.error(data.msg, '操作失败')
            }
        }
    })
}

// Local Storage functions
// Set proper body class and plugins based on user configuration
$(document).ready(function () {
    if (localStorageSupport()) {

        var collapse = localStorage.getItem("collapse_menu");
        var fixedsidebar = localStorage.getItem("fixedsidebar");
        var fixednavbar = localStorage.getItem("fixednavbar");
        var boxedlayout = localStorage.getItem("boxedlayout");
        var fixedfooter = localStorage.getItem("fixedfooter");
        menuList = JSON.parse(localStorage.getItem("menuList"));
        $.buildMenu(menuList);
        // MetisMenu
        var sideMenu = $('#side-menu').metisMenu();
        $('.myMenu').on('click', function (e) {
            let dataset = e.currentTarget.dataset;
            if (dataset.url) {
                if (dataset.url.indexOf("http") != -1) {
                    window.open(dataset.url, "_blank");
                    return;
                }
                if (dataset.frame == 'true') {
                    $('.page-heading').hide()
                    $('#index_center').empty()
                    $('#index_center').html(`<iframe onload="iframeLoad(this)" src="/portal/portal_index2.html?url=${dataset.url}" style="width: 100%; height: 100%;" frameborder='0' border='1'></iframe>`);
                } else {
                    if(dataset.url.indexOf('profile') != -1){
                        centerLoad(dataset.url, undefined, '个人信息', dataset.header, true)
                    } else {
                        centerLoad(dataset.url, dataset.menuid, undefined, dataset.header)
                    }
                }
            }
        });

        var body = $('body');

        if (fixedsidebar == 'on') {
            body.addClass('fixed-sidebar');
            $('.sidebar-collapse').slimScroll({
                height: '100%',
                railOpacity: 0.9
            });
        }

        if (collapse == 'on') {
            if (body.hasClass('fixed-sidebar')) {
                if (!body.hasClass('body-small')) {
                    body.addClass('mini-navbar');
                }
            } else {
                if (!body.hasClass('body-small')) {
                    body.addClass('mini-navbar');
                }

            }
        }

        if (fixednavbar == 'on') {
            $(".navbar-static-top").removeClass('navbar-static-top').addClass('navbar-fixed-top');
            body.addClass('fixed-nav');
        }

        if (boxedlayout == 'on') {
            body.addClass('boxed-layout');
        }

        if (fixedfooter == 'on') {
            $(".footer").addClass('fixed');
        }
    }
});

// check if browser support HTML5 local storage
function localStorageSupport() {
    return (('localStorage' in window) && window['localStorage'] !== null)
}

// For demo purpose - animation css script
function animationHover(element, animation) {
    element = $(element);
    element.hover(
        function () {
            element.addClass('animated ' + animation);
        },
        function () {
            //wait for animation to finish before removing classes
            window.setTimeout(function () {
                element.removeClass('animated ' + animation);
            }, 2000);
        });
}

function SmoothlyMenu() {
    if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) {
        // Hide menu in order to smoothly turn on when maximize menu
        $('#side-menu').hide();
        // For smoothly turn on menu
        setTimeout(
            function () {
                $('#side-menu').fadeIn(400);
            }, 200);
    } else if ($('body').hasClass('fixed-sidebar')) {
        $('#side-menu').hide();
        setTimeout(
            function () {
                $('#side-menu').fadeIn(400);
            }, 100);
    } else {
        // Remove all inline style from jquery fadeIn function to reset menu state
        $('#side-menu').removeAttr('style');
    }
}

// Dragable panels
function WinMove() {
    var element = "[class*=col]";
    var handle = ".ibox-title";
    var connect = "[class*=col]";
    $(element).sortable(
        {
            handle: handle,
            connectWith: connect,
            tolerance: 'pointer',
            forcePlaceholderSize: true,
            opacity: 0.8
        })
        .disableSelection();
}